package com.dyz.leetcode;

import java.util.*;
import java.util.concurrent.ThreadLocalRandom;

public class IsValid20 {
    public static void main(String[] args) {
        boolean valid = new IsValid20().isValid("([)]");
        System.out.println(valid);
    }
    public boolean isValid(String s) {
        if(s==null){return false;}
        int len = s.length();
        if(len%2!=0){return false;}
        Map<Character, Character> pairs = new HashMap<Character, Character>(){{
            put(')', '(');
            put(']', '[');
            put('}', '{');
        }};
        Stack<Character> stack = new Stack<>();
        for(int i=0; i<len; i++){
            char ch = s.charAt(i);
            if(pairs.containsKey(ch)){
                if(stack.isEmpty()||stack.peek()!=pairs.get(ch)){
                    return false;
                }
                stack.pop();
            }else {
                stack.push(ch);
            }
        }
        return stack.isEmpty();
    }
}
